package cn.lyjuan.archetypes.bms.web.property;

import cn.lyjuan.archetypes.bms.web.util.AppUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;

/**
 * 将实现了{@link IShareProperties}接口的资源Bean放入ServletContext中共享
 */
@Aspect
@Component
public class PropertiesLoader
{
    private static Logger log = LogManager.getLogger(PropertiesLoader.class);

    @Autowired
    private ApplicationContext ctx;

    /**
     * 在contoller包下所有类的所有方法执行后执行
     */
    @Before("execution(* cn.lyjuan.archetypes.bms.web.controller.*.*(..))")
    public void loadProperties()
    {
        /*
         * 在web 项目中（spring mvc），系统会存在两个容器，一个是root application context ,
         * 另一个就是我们自己的 projectName-servlet context（作为root application context的子容器）
         */
//        if (contextRefreshedEvent.getApplicationContext().getParent() != null)
//            return;

        Map<String, IShareProperties> beans = ctx.getBeansOfType(IShareProperties.class);

        if (log.isDebugEnabled())
            log.debug("load: " + beans);

        if (beans.isEmpty())
            return;

        HttpServletRequest req = AppUtils.req();
        for (Iterator<Map.Entry<String, IShareProperties>> it = beans.entrySet().iterator(); it.hasNext(); )
        {
            Map.Entry<String, IShareProperties> entry = it.next();
            req.setAttribute(entry.getKey(), entry.getValue());
        }

        // 遍历属性转换为 map

        /*Map<String, Map<String, Object>> all = new HashMap<>(beans.size());
        Map<String, Object> map = null;
        HttpServletRequest req = AppUtils.req();
        // 将所有共享资源放入ServletContext中共享
        for (Iterator<Map.Entry<String, IShareProperties>> it = beans.entrySet().iterator(); it.hasNext(); )
        {
            Map.Entry<String, IShareProperties> entry = it.next();

            String name = entry.getKey();
            Object val = entry.getValue();
            map = new HashMap<>();

            Field[] fields = val.getClass().getDeclaredFields();

            for (Field f : fields)
            {
                boolean isAcc = f.isAccessible();
                f.setAccessible(true);
                // 只能放 String 值
                String obj = StringUtils.nullToStr(ReflectUtils.getValueNoThrow(val, f.getName()));
                map.put(f.getName(), obj);
                f.setAccessible(isAcc);
            }

            all.put(name, map);
        }

        AppUtils.req().setAttribute("shareProperties", all);*/
    }
}
